﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Data.Linq.SqlClient;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using IntraVision.Web.Filter;
using Model;

[Security]
public class NotarialFormRangeController : TableController<NotarialServiceDataContext, NotarialFormRange>
{
    protected override IQueryable ConvertQueryToResult(NotarialServiceDataContext dc, IQueryable<NotarialFormRange> query)
    {
        return (from q in query    
                select new
                {
                       Id = q.Id,
                       Name = q.Name,
                       CreateDate = q.CreateDate,
                       NotUsedCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.NotUsed),
                       UsedCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.Used),
                       DublicateCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.Dublicate),
                       DefectCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.Defect),
                       BadCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.Bad),
                       LostCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.Lost),
                       MissingCount = q.NotarialForm.Count(nf => nf.StatusId == (int)NotarialForm.NotarialFormStatusType.Missing),
                       TotalCount = q.NotarialForm.Count(),
                });        
    }

    public override void Default()
    {        
        List();     
    }

    private long GetNumber(string str)
    {
        return long.Parse(str.TrimStart().Substring(4).Trim());
    }

    public void ConvertOld()
    {
        var data = GetOldDataToConvert();
        using (var dc = new NotarialServiceDataContext())
        {
            foreach (var start in data.Keys)
            {
                var end = data[start];
                var nr = new NotarialFormRange
                             {
                                 CreateDate = DateTime.Now,
                                 StartNumber = GetNumber(start),
                                 EndNumber = GetNumber(end)
                             };

                BeforeSubmit(dc, nr);
                dc.NotarialFormRange.InsertOnSubmit(nr);
                dc.SubmitChanges();
                AfterSubmit(dc, nr);
            }
        }
    }

    private Dictionary<string,string> GetOldDataToConvert()
    {
        var result = new Dictionary<string, string>();
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString))
        {
            connection.Open();
            using (var command = new SqlCommand("select * from [dbo].[nrtemp]", connection))
            {
                using (var dr = command.ExecuteReader())
                {
                    while (dr.Read())
                        result.Add(dr["F2"].ToString(), dr["F3"].ToString());
                }
            }
            connection.Close();
        }
        return result;
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, NotarialFormRange entity)
    {
        if (entity.StartNumber > entity.EndNumber)
            throw new ArgumentOutOfRangeException("Первый номер пачки не может быть больше последнего.");

        if (dc.NotarialFormRange.Any(r => r.Id != entity.Id
                                      && ((entity.StartNumber >= r.StartNumber && entity.StartNumber <= r.EndNumber)
                                          || (entity.EndNumber >= r.StartNumber && entity.EndNumber <= r.EndNumber)
                                          || (entity.EndNumber >= r.EndNumber && entity.StartNumber <= r.StartNumber))))
            throw new ArgumentOutOfRangeException("Диапазон номеров бланков пересекается с существующим."); 

        entity.Name = string.Format("{2}{0} - {2}{1}", entity.StartNumber.AddLeadingZero(7), entity.EndNumber.AddLeadingZero(7), "77AA");
        entity.SerialNumberId = 1;
     
        base.BeforeSubmit(dc, entity);
    }

    protected override void AfterSubmit(NotarialServiceDataContext dc, NotarialFormRange entity)
    {
        AddNotarialForms(dc, entity);
        DeleteNotarialForms(dc, entity);

        dc.SubmitChanges();

        base.AfterSubmit(dc, entity);
    }

    protected void AddNotarialForms(NotarialServiceDataContext dc, NotarialFormRange entity)
    {
        var formsIds = entity.NotarialForm.Select(i => i.Name).ToArray();
        var user = Session["User"] as User;

        for (var i = entity.StartNumber; i <= entity.EndNumber; i++)
            if (!formsIds.Contains(i))
                entity.NotarialForm.Add(
                    new NotarialForm
                    {
                        Name = i,
                        StatusId = 1,
                        SerialNumberId = entity.SerialNumberId,
                        UserId = user.Id,
                    });
    }

    protected void DeleteNotarialForms(NotarialServiceDataContext dc, NotarialFormRange entity)
    {
        var formsToDelete = dc.NotarialForm.Where(f => f.RangeId == entity.Id
                                                  && (f.Name < entity.StartNumber || f.Name > entity.EndNumber));
        dc.NotarialForm.DeleteAllOnSubmit(formsToDelete);
    }

    protected override void CreateFilterConditions(NotarialServiceDataContext dc)
    {
        base.CreateFilterConditions(dc);

        Filter = new Filter<NotarialFormRange>();
        var fc = Filter.Conditions;
        fc.Add(new StringFilterCondition<NotarialFormRange>("name", "Номер пачки"));
    }         
}
